<script lang="ts" setup>
import { BSDataTypeEnum, FormTypeEnum, RecordTypeEnum } from "@@/constants/other-keys";
import { BasicClassValueField } from '@@/apis/basic-data/types';
import { computed, ref } from 'vue';
import { VxeTablePropTypes } from 'vxe-table';
import { cloneDeep } from "lodash";
import { v4 as uuidv4 }  from "uuid";
import { ElMessage, ElMessageBox } from "element-plus";
import XEUtils from "xe-utils";
import "@@/components/plugins/EditDownModal"
import basicDrawer from "@@/components/plugins/DrawerParamAdd.vue"
import { watch } from "vue";

interface Props {
  isEdit: boolean
  staticFlag: number
}
const props = defineProps<Props>()
const emit = defineEmits(["updateData"])

const dialogType = ref(FormTypeEnum.CREATE)
const fieldTableRef = ref();
const validRules = ref<VxeTablePropTypes.EditRules>({
  code: [
    { required: true, message: '参数名不能为空', trigger: "blur" },
    { message: "第一个字符必须是字母（大小写均可）或下划线 _", pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, trigger: "blur" }
  ],
  typeCode: [
    { required: true, message: '数据类型必选择' },
  ]
})
const tableData = ref<BasicClassValueField[]>([]);
const DEFAULT_ITEM_VALUE: BasicClassValueField = {
  name: undefined,
  code: undefined,
  type: BSDataTypeEnum.Base,
  typeId: undefined,
  typeCode: undefined,
  separator: undefined,
  recordType: RecordTypeEnum.Base,
  staticFlag: props.staticFlag,
  value: "",
  sort: tableData.value.length + 1
}
const dialogVisible = ref<boolean>(false);
// 页面新增class参数信息
const insertFields = ref<BasicClassValueField[]>([]);
const updateFields = ref<BasicClassValueField[]>([]);
const removeFields = ref<BasicClassValueField[]>([]);
// 编辑的参数
const editParamValue = ref<BasicClassValueField>()

const deleteBtn = computed(() => {
  if (fieldTableRef.value) {
    const selectRecords = fieldTableRef.value.getCheckboxRecords()
    return selectRecords.length > 0
  }
  return false
})

// 保存参数
const handleConfirm = (formData: BasicClassValueField) => {
  if (formData.id == undefined) {
    // 新增
    handleCreateTask(cloneDeep(formData))
  } else {
    tableData.value.forEach(item => {
      if (item.id == formData.id) {
        fieldTableRef.value.setRow(item, formData)
        return
      }
    })
  }
  dialogVisible.value = false
}
// 新建参数
const handleCreateTask = (record?: BasicClassValueField) => {
  if (record == undefined) {
    record = cloneDeep(DEFAULT_ITEM_VALUE)
  }
  record.id = uuidv4()
  record.isAdd = true
  tableData.value = getFullData()
  tableData.value.push(record)
  insertFields.value.push(record)
  fieldTableRef.value.setEditRow(record, 'code');
}
// 弹窗清空数据
const closeDialog = () => {
  dialogVisible.value = false
}
const handleRemoveNode = (id: string) => {
  XEUtils.eachTree(tableData.value, item => {
    if (id === item.id) {
      removeFields.value.push(item)
    }
  }, { children: 'children' })
  tableData.value = tableData.value.filter(item => item.id != undefined && item.id != id)
  insertFields.value = insertFields.value.filter(item => item.id != undefined && item.id != id)
  updateFields.value = updateFields.value.filter(item => item.id != undefined && item.id != id)
}
// 批量删除参数
const handleMultipleDelete = () => {
  if (fieldTableRef.value) {
    const selectRecords = fieldTableRef.value.getCheckboxRecords()
    const ids: string[] = []
    const names: string[] = []
    selectRecords.forEach((item) => {
      ids.push(item.id as string)
      names.push(item.code as string)
    })
    ElMessageBox.confirm(`正在删除参数：${names.join("，")}，确认删除？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      const delIds: number[] = []
      XEUtils.eachTree(selectRecords, item => {
        if (!removeFields.value.some(obj => item.id === obj.id)) {
          delIds.push(item.id)
          removeFields.value.push(item)
        }
      }, { children: 'children' })
      insertFields.value = insertFields.value.filter(item => !delIds.includes(item.id))
      updateFields.value = updateFields.value.filter(item => !delIds.includes(item.id))
      tableData.value = getFullData().filter(item => !delIds.includes(item.id))
    })
  }
}
// 校验参数
const handleValidParam = () => {
  return new Promise(async (resolve, reject) => {
    if (!fieldTableRef.value) return false
    const valueErrors = await fieldTableRef.value.validate(true);
    if (valueErrors) {
      ElMessage.warning(props.staticFlag == 0 ? "参数校验未通过" : "静态参数校验未通过")
      reject()
    }
    resolve(true)
  })
}
// 通用函数：更新数据顺序和 sort 字段
function updateSortField(resultData: BasicClassValueField[]) {
  return resultData.map((item, index) => {
    return { ...item, sort: index }; // 直接添加 sort 字段
  });
}
// 参数
const getFieldParam = () => {
  // 获取完整数据并更新顺序
  const resultTableData = getFullData();
  const sortedResultData = updateSortField(resultTableData);

  // 更新 insertFields 中的 sort 字段
  insertFields.value = insertFields.value.map(item => {
    const sortedItem = sortedResultData.find(sorted => sorted.id === item.id);
    if (sortedItem) {
      return { ...item, sort: sortedItem.sort + 1 };
    }
    return item;
  });

  // 将不在 insertFields 中的记录放入 updateFields
  updateFields.value = sortedResultData.filter(item =>
    !insertFields.value.some(insertItem => insertItem.id === item.id)
  );

  // 清理 insertFields
  const _insertFields = cloneDeep(insertFields.value);
  _insertFields.forEach(item => {
    delete item.id;
  });

  // 过滤掉 isAdd 的记录
  updateFields.value = updateFields.value.filter(item => !item.isAdd);
  removeFields.value = removeFields.value.filter(item => !item.isAdd);

  // 返回更新后的数据
  return {
    insertFields: _insertFields,
    updateFields: updateFields.value,
    removeFields: removeFields.value
  };
}

const handleAddDialog = () => {
  dialogType.value = FormTypeEnum.CREATE
  dialogVisible.value = true
}

const handleEditDialog = (params: BasicClassValueField) => {
  dialogType.value = FormTypeEnum.EDIT
  dialogVisible.value = true
  editParamValue.value = cloneDeep(params)
}

const initFieldData = (params: BasicClassValueField[]) => {
  tableData.value = cloneDeep(params)
}

const clearData = () => {
  tableData.value = []
  insertFields.value = []
  updateFields.value = []
  removeFields.value = []
}

const getFullData = (): BasicClassValueField[] => {
  return fieldTableRef.value.getFullData()
}

// 获取参数
defineExpose({ getFieldParam, handleValidParam, handleCreateTask, handleRemoveNode, handleAddDialog, handleEditDialog, initFieldData, clearData })

watch(
  () => tableData.value,
  () => {
    emit("updateData", cloneDeep(tableData.value))
  },
  { deep: true }
)
</script>
<template>
  <div class="cpi-content-main">
    <div v-if="props.isEdit" class="cpi-content-toolbar mb-3">
      <el-space>
        <el-button type="primary" plain @click="handleCreateTask()">新建参数</el-button>
        <el-button :disabled="!deleteBtn" type="danger" @click="handleMultipleDelete">批量删除</el-button>
      </el-space>
    </div>
    <div class="cpi-content-table">
      <vxe-table class="cpi-table" ref="fieldTableRef" height="auto" show-overflow highlight-hover-row show-header auto-resize keep-source size="small" :edit-rules="validRules" :data="tableData" :mouse-config="{ selected: false }"  :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" :row-config="{ drag: isEdit, useKey: true }" :row-drag-config="{ trigger: 'cell', showGuidesStatus: false }" :align="'left'" header-align="left"
      >
        <vxe-table-column :visible="props.isEdit" type="checkbox" width="40" />
        <vxe-table-column type="seq" title="序号" width="60" :drag-sort="isEdit" :align="'center'" header-align="center" />
        <vxe-table-column field="code" title="参数名">
          <template #default="{ row }">
            <el-input v-if="props.isEdit" v-model="row.code" />
            <span v-else>{{ row.code }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="name" title="参数描述">
          <template #default="{ row }">
            <el-input v-if="props.isEdit" v-model="row.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="type" title="分类" formatter="formatType" />
        <vxe-table-column field="separator" title="参数连接符" />
        <vxe-table-column v-if="props.isEdit" field="typeCode" title="数据类型" :cell-render="{ name: 'EditDownModal' }" />
        <vxe-table-column v-else field="typeCode" title="数据类型">
          <template #default="{ row }">
            {{ row.typeCode }}
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>

    <basicDrawer ref="basicDrawerRef" :visible="dialogVisible" :staticFlag="props.staticFlag" :dialogType="dialogType" :default-info="editParamValue" @closeDialog="closeDialog" @handleConfirm="handleConfirm" />
  </div>
</template>
<style lang="scss" scoped>
.cpi-content-main {
  min-height: 380px !important;
  display: flex;
  flex-direction: column;
}
.cpi-content-table {
  flex: 1;
  max-height: 400px;
}
</style>
